package com.glqiang.security;

import com.alibaba.fastjson2.annotation.JSONField;
import com.glqiang.constant.Constants;
import com.glqiang.domain.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义用户信息类，实现了UserDetails接口
 * @author glq1218
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomUserDetails implements UserDetails {
    /**
     * 用户信息
     */
    private User user;

    /**
     * 权限信息
     */
    private List<String> permissions;

    public CustomUserDetails(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    /**
     * 获取用户的权限信息
     *
     * @return 用户的权限信息集合
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 不能返回null
        // return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        if (authorities != null) {
            return authorities;
        }

        // Stream流
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    /**
     * 获取密码
     * @return 密码
     */
    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    /**
     * 获取用户名
     * @return 用户名
     */
    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    /**
     * 账号是否内有过期
     * @return 是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账号是否锁定
     * 数据库中的is_disabled字段 描述用户账号是否可用
     * @return true 账号未锁定 false 账号锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return Constants.SUCCESS.equals(this.user.getIsDisabled());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
